package com.five.bi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.five.bi.config.DataSourceConfig;
import com.five.bi.mapper.TestMapper;
import com.five.bi.model.DatasourceInfo;
import com.five.bi.model.TStockSum;
import com.five.bi.service.DatasourceInfoService;
import com.five.bi.utils.DynamicDataSource;
import com.five.bi.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Mr.Lee
 * @Date: 2022/8/13 12:13
 * @Description: 数据源切换以及测试连接
 */
@RestController
@RequestMapping("/api/v1/datasource")
public class DynamicDataSourceController {
    @Autowired
    private DynamicDataSource dynamicDataSource;
    @Resource
    private TestMapper testMapper;

    @Autowired
    private DataSourceConfig dataSourceConfig;

    @Autowired
    private DatasourceInfoService datasourceInfoService;

    /**
     * 测试数据源的切换
     *
     * @param datasourceInfo
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    @PostMapping("/link")
    public JsonData link(@RequestBody DatasourceInfo datasourceInfo) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //切换数据源之前先清空
        DynamicDataSource.clearDataSource();
        //切换数据源
        dynamicDataSource.createDataSource(datasourceInfo);
        //切换数据源之后应该判断数据库中是否有此值，如果有不用任何操作，如果没有则添加一条记录

//        DatasourceInfo dataType = datasourceInfoService.getOne(new QueryWrapper<DatasourceInfo>().eq("data_type", datasourceInfo.getDataType()));
//        if (dataType==null) {
//            datasourceInfo.setDataDriver(String.valueOf(dynamicDataSource.getConnection()));
//            datasourceInfoService.save(datasourceInfo);
//        }
        System.out.println("当前数据源:" + dynamicDataSource.getConnection());
        return JsonData.buildSuccess("当前数据源:" + dynamicDataSource.getConnection());
    }

    /**
     * 测试切换不同数据源之后的查询是否能成功
     *
     * @return
     * @throws SQLException
     */
    @GetMapping("/test")
    public JsonData test() throws SQLException {
        System.out.println("当前数据源为：" + dynamicDataSource.getConnection());
        List<TStockSum> tStockSums = testMapper.selectList(new QueryWrapper<>(null));
        return JsonData.buildSuccess(tStockSums);
    }
}

